package com.ruoyi.web.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.domain.mes.delivery.DeliveryDetails;
import com.ruoyi.web.mapper.DeliveryMapper;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.service.*;
import com.ruoyi.web.vo.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/delivery")
public class DeliveryController extends BaseController {
    @Resource
    private DeliveryService deliveryService;

    @Resource
    private DeliveryDetailsService deliveryDetailsService;

    @Resource
    private DeliveryDetailService deliveryDetailService;

    @Resource
    private ProducePieceService producePieceService;

    @Resource
    private ProduceService produceService;

    @Resource
    private DeliveryMapper deliveryMapper;

//    @Resource
//    private DeliveryBooksService deliveryBooksService;

    @Resource
    private MesConfigMapper configMapper;

    @PostMapping(value = "/list")
    public TableDataInfo list(@RequestBody Map<String, String> params) {
        String code = params.get("code");            // 发货单编码
        String bookName = params.get("bookName");  // 书刊名称
        String bookCode = params.get("bookCode");    // 书刊编码
        String status = params.get("status");        // 状态
        String produceNo = params.get("produceNo");
        String deliveryDate = params.get("deliveryDate");//发货日期
        String yearMonth = params.get("yearMonth");//发货日期
        Delivery delivery = new Delivery();
        if (StringUtils.isNotEmpty(yearMonth)) {
            String year = yearMonth.substring(0, 4);
            String month = yearMonth.substring(5);
            delivery.setYear(Integer.valueOf(year));
            delivery.setMonth(Integer.valueOf(month));
        }
        delivery.setCode(code);
        delivery.setBookCode(bookCode);
        delivery.setBookName(bookName);
        delivery.setSearchDate(deliveryDate);
        if (StringUtils.isNotEmpty(status)) {
            delivery.setStatus(Integer.parseInt(status));
        }
        delivery.setProduceNo(produceNo);
        startPage(params);
        List<Delivery> deliverys = deliveryMapper.selectDeliveryList(delivery);
        if (deliverys.size() > 0) {
            Delivery deliverysSum = deliveryMapper.selectDeliveryListSum(delivery);
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("quantity", deliverysSum.getQuantity().toString()); // 发货数量
            hashMap.put("orderCount", deliverysSum.getOrderCount()); // 订单数量
            hashMap.put("lingCount", deliverysSum.getLingCount().toPlainString()); // 发货纸令数
            deliverys.get(0).setHashMap(hashMap);
        }
        TableDataInfo data = getDataTable(deliverys);
//        TableDataInfo data = getDataTable(deliveryService.list(new QueryWrapper<Delivery>().lambda()
//                .like(StringUtils.isNotEmpty(code), Delivery::getCode, code)
//                .like(StringUtils.isNotEmpty(bookName), Delivery::getBookName, bookName)
//                .like(StringUtils.isNotEmpty(bookCode), Delivery::getBookCode, bookCode)
//                .eq(StringUtils.isNotEmpty(status), Delivery::getStatus, status)
//                .orderByDesc(Delivery::getCode)
//        ));
        return data;
    }


    @GetMapping(value = "/detailslist")
    public TableDataInfo detailslist(DeliveryDetails deliveryDetails) {
        startPage();  // 此方法配合前端完成自动分页
        List<DeliveryDetails> data = deliveryDetailsService.getDeliveryDetailsList(deliveryDetails);
        return getDataTable(data);
    }


    @GetMapping(value = "/getDeliveryDetail")
    public TableDataInfo getDeliveryDetail(Delivery delivery) {
        startPage();
        List<Delivery> deliverys = deliveryMapper.selectDeliveryDetail(delivery);
        return getDataTable(deliverys);
    }


    @PostMapping(value = "/add")
    @Transactional
    public AjaxResult add(@RequestBody Delivery delivery) {
        if (delivery.getId() == null) {
            delivery.setId(UUID.randomUUID().toString().replace("-", ""));
            delivery.setCreateBy(SecurityUtils.getUsername());
            delivery.setCreateTime(DateUtils.getNowDate());

            Map<String, Object> map = new HashMap<>();
            map.put("columnName", "code");
            map.put("tableName", "mes_delivery");
            int maxNum = configMapper.getDayMaxId(map);//.getMouthMaxId(map);//每天都从1开始

            String code = PinYinUtils.getCodeNormal(maxNum, "FHGL");
            delivery.setCode(code);

            if (delivery.getDeliveryDetailList() != null && delivery.getDeliveryDetailList().size() != 0) {
                for (DeliveryDetail deliveryDetail : delivery.getDeliveryDetailList()) {
                    deliveryDetail.setDeliveryId(delivery.getId());
                    deliveryDetail.setCreateBy(SecurityUtils.getUsername());
                    deliveryDetail.setCreateTime(DateUtils.getNowDate());
                }
            }
//            if (delivery.getDeliveryBooksList() != null && delivery.getDeliveryBooksList().size() != 0) {
//                for (DeliveryBooks deliveryBooks : delivery.getDeliveryBooksList()) {
//                    deliveryBooks.setDeliveryId(delivery.getId());
//                    deliveryBooks.setCreateBy(SecurityUtils.getUsername());
//                    deliveryBooks.setCreateTime(DateUtils.getNowDate());
//                }
//            }
        } else {
            delivery.setUpdateTime(DateUtils.getNowDate());
            delivery.setUpdateBy(SecurityUtils.getUsername());
        }

        deliveryService.saveOrUpdate(delivery);
        if (delivery.getDeliveryDetailList() != null && delivery.getDeliveryDetailList().size() != 0) {
            deliveryDetailService.remove(new QueryWrapper<DeliveryDetail>().lambda().eq(DeliveryDetail::getDeliveryId, delivery.getId()));
            deliveryDetailService.saveBatch(delivery.getDeliveryDetailList());
        }
        if (delivery.getDeliveryDetailList() != null && delivery.getDeliveryDetailList().size() != 0) {
            for (DeliveryDetail deliveryDetail : delivery.getDeliveryDetailList()) {
                //判断总发货数量不得大于生产单订单数量
                List<DeliveryDetail> list = deliveryDetailService.list(new QueryWrapper<DeliveryDetail>().lambda()
                        .eq(DeliveryDetail::getProduceId, deliveryDetail.getProduceId()));
                if (list != null && list.size() > 0) {
                    Long total = (long) list.stream().mapToDouble(DeliveryDetail::getQuantity).sum();
                    produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getDeliveryCount, total).eq(Produce::getProduceId, deliveryDetail.getProduceId()));

                    // double percentage = 0.90;
                    // long maxAllowedValue = (long) (deliveryDetail.getOrderCount() * percentage);
                    long maxAllowedValue = (long) (deliveryDetail.getOrderCount());
                    if (total >= maxAllowedValue) {
                        // 发货完成
                        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, "18").eq(Produce::getProduceId, deliveryDetail.getProduceId()));
                    } else {
                        // 发货中
                        produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getStatus, "17").eq(Produce::getProduceId, deliveryDetail.getProduceId()));
                    }
                }
            }
        }
//        if (delivery.getDeliveryBooksList() != null && delivery.getDeliveryBooksList().size() != 0) {
//            deliveryBooksService.remove(new QueryWrapper<DeliveryBooks>().lambda().eq(DeliveryBooks::getDeliveryId, delivery.getId()));
//            deliveryBooksService.saveBatch(delivery.getDeliveryBooksList());
//        }

        return AjaxResult.success("添加成功", delivery.getId());
    }

    @PostMapping(value = "/updateStatus")
    public AjaxResult updateStatus(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        String status = params.get("status");
        deliveryService.update(new UpdateWrapper<Delivery>().lambda().set(Delivery::getStatus, status).eq(Delivery::getId, id));
//        if (status.equals("2")) { // 已提交
//            List<Delivery> deliverys = deliveryMapper.selectQuantityById(id);
//            for (Delivery delivery : deliverys) {
//                deliveryMapper.updateProduceDeliveryCount(delivery);
//            }
//        }

        return AjaxResult.success("更新成功");
    }

    @PostMapping(value = "/getById")
    public AjaxResult getById(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        Delivery delivery = deliveryService.getById(id);
        List<DeliveryDetail> deliveryDetailList = deliveryDetailService.list(new QueryWrapper<DeliveryDetail>().lambda().eq(DeliveryDetail::getDeliveryId, delivery.getId()).orderByDesc(DeliveryDetail::getCreateTime));
        // List<DeliveryBooks> deliveryBooksList = deliveryBooksService.list(new QueryWrapper<DeliveryBooks>().lambda().eq(DeliveryBooks::getDeliveryId, delivery.getId()).orderByDesc(DeliveryBooks::getCreateTime));

        for (DeliveryDetail deliveryDetail : deliveryDetailList) {
            Produce produce = produceService.getById(deliveryDetail.getProduceId());
            String countNum = produce.getDeliveryCount() == null ? "0" : produce.getDeliveryCount().toString();
            deliveryDetail.setDeliveryCount(countNum);
        }
        delivery.setDeliveryDetailList(deliveryDetailList);
        // delivery.setDeliveryBooksList(deliveryBooksList);
        return AjaxResult.success("查询成功", delivery);
    }

    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        String produceNo = "";
        // 查询生产单编号
        List<DeliveryDetail> detailList = deliveryDetailService.list(new QueryWrapper<DeliveryDetail>().lambda().eq(DeliveryDetail::getDeliveryId, id).orderByDesc(DeliveryDetail::getCreateTime));
        if (detailList != null && detailList.size() > 0) {
            produceNo = detailList.get(0).getProduceNo();
        }
        deliveryService.removeById(id);
        deliveryDetailService.remove(new QueryWrapper<DeliveryDetail>().lambda().eq(DeliveryDetail::getDeliveryId, id));

        // 删除更改多次发货的，当前累积发货数量
        List<DeliveryDetail> deliveryDetailList = deliveryDetailService.list(new QueryWrapper<DeliveryDetail>().lambda().eq(DeliveryDetail::getProduceNo, produceNo).orderByAsc(DeliveryDetail::getCreateTime));
        for (DeliveryDetail deliveryDetail : deliveryDetailList) {
            deliveryDetailService.update(new UpdateWrapper<DeliveryDetail>().lambda().set(DeliveryDetail::getDeliveryCount, deliveryDetail.getDeliveryCount()).eq(DeliveryDetail::getId, deliveryDetail.getId()));
            // 更改生产单累积字段，用于列表显示
            List<DeliveryDetail> list = deliveryDetailService.list(new QueryWrapper<DeliveryDetail>().lambda()
                    .eq(DeliveryDetail::getProduceId, deliveryDetail.getProduceId()));
            if (list != null && list.size() > 0) {
                Long total = (long) list.stream().mapToDouble(DeliveryDetail::getQuantity).sum();
                produceService.update(new UpdateWrapper<Produce>().lambda().set(Produce::getDeliveryCount, total).eq(Produce::getProduceId, deliveryDetail.getProduceId()));
            }
        }

        return AjaxResult.success("删除成功");
    }

    @PostMapping(value = "/export")
    public void export(HttpServletResponse response, @RequestBody Map<String, String> params) {//Delivery delivery
//        String code = delivery.getCode();            // 发货单编码
//        String bookName = delivery.getBookName();  // 书刊名称
//        String bookCode = delivery.getBookCode();    // 书刊编码
//        Integer status = delivery.getStatus();        // 状态
//        String produceNo = delivery.getProduceNo();
//        String searchDate =delivery.getSearchDate();//发货日期
//        List<Delivery> list = deliveryService.list(new QueryWrapper<Delivery>().lambda()
//                .like(StringUtils.isNotEmpty(code), Delivery::getCode, code)
//                .like(StringUtils.isNotEmpty(bookName), Delivery::getBookName, bookName)
//                .like(StringUtils.isNotEmpty(bookCode), Delivery::getBookCode, bookCode)
//                .orderByDesc(Delivery::getCode));
        String code = params.get("code");            // 发货单编码
        String bookName = params.get("bookName");  // 书刊名称
        String bookCode = params.get("bookCode");    // 书刊编码
        String status = params.get("status");        // 状态
        String produceNo = params.get("produceNo");
        String deliveryDate = params.get("deliveryDate");//发货日期
        Delivery delivery = new Delivery();
        delivery.setCode(code);
        delivery.setBookCode(bookCode);
        delivery.setBookName(bookName);
        delivery.setSearchDate(deliveryDate);
        if (StringUtils.isNotEmpty(status)) {
            delivery.setStatus(Integer.parseInt(status));
        }
        delivery.setProduceNo(produceNo);
        List<Delivery> list = deliveryMapper.selectDeliveryList(delivery);
        if (list.size() > 0) {
            int no = 1;
            for (Delivery delivery1 : list) {
                delivery1.setNo(no);
                no++;
            }
        }
        ExcelUtil<Delivery> util = new ExcelUtil<>(Delivery.class);
        util.exportExcel(response, list, "发货单信息数据");
    }
}
